using System;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using Slaks.VectorBasics.Containers;

namespace Slaks.VectorBasics.Category
{
	public class CategoryReader
	{
		private static readonly string FileNameCategoryPattern = @"\s*(?<filename>.+?)\s+(?<category>\w+)";
		private static readonly string FileNameGroup = "filename";
		private static readonly string CategoryGroup = "category";
		private static Regex m_regex = new Regex(FileNameCategoryPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

		private static int m_numberOfDistinctCategories = 0;
		private static ArrayList m_categoryList;

		public static Document2CategoryMap ReadCategoryFile(string filename)
		{
			StreamReader reader = null;
			Document2CategoryMap doc2category = null;
			try
			{
				reader = new StreamReader(filename);
				doc2category = new Document2CategoryMap();
				CategoryFiller(reader, doc2category);
			}
			catch (Exception ex)
			{
				throw ex;
			}
			finally
			{
				if (reader != null) reader.Close();
			}

			return doc2category;
		}

		private static void CategoryFiller(StreamReader reader, Document2CategoryMap map)
		{
			Hashtable category = new Hashtable();
			object dummy = new object();

			string line;
			string m_fileName;
			string m_category;
			while ((line = reader.ReadLine()) != null)
			{
				if (line == String.Empty) continue;
				Match m = m_regex.Match(line);
				if (m.Groups.Count < 2) continue;
				m_fileName = m.Groups[FileNameGroup].Value;
				m_category = m.Groups[CategoryGroup].Value;

				if (category.ContainsKey(m_category) == false) category.Add(m_category, dummy);

				map.Add(m_fileName, m_category);
			}

			//set the number of unique categories
			m_numberOfDistinctCategories = category.Count;

			m_categoryList = new ArrayList(category.Keys);
		}

		public static int GetNumberOfDistinctCategories()
		{
			return m_numberOfDistinctCategories;
		}

		public static IList GetCategoryList()
		{
			return m_categoryList;
		}
	}


}